package com.verlet.springbootdemo.sse;

import com.verlet.springbootdemo.entity.Temperature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author Verlet
 * @date 2023-02-02 00:56
 */
@Slf4j
@RestController
public class TemperatureController {
    private final Set<SseEmitter> clients = new CopyOnWriteArraySet<>();

    @GetMapping("/temperature-stream")
    public SseEmitter events(HttpServletRequest request) {
        SseEmitter sseEmitter = new SseEmitter();
        clients.add(sseEmitter);
        sseEmitter.onTimeout(() -> clients.remove(sseEmitter));
        sseEmitter.onCompletion(() -> clients.remove(sseEmitter));
        return sseEmitter;
    }

    @Async
    @EventListener
    public void handleMessage(Temperature temperature) {
        List<SseEmitter> deadEmitters = new ArrayList<>();
        clients.forEach(sseEmitter -> {
            try {
                sseEmitter.send(temperature, MediaType.APPLICATION_JSON);
            } catch (Exception e) {
                log.error(e.getMessage());
                deadEmitters.add(sseEmitter);
            }
        });
        deadEmitters.forEach(clients::remove);
    }
}
